# -*- coding: utf-8-unix; fill-column: 95; -*-

###############################################################################################
#
# This file is part of Escapade Trip Planner, a social web application for creating and
# sharing motorcycle roadmaps.
#
# Copyright © 2011, Pierre-François Gomez <pef.gomez@gmail.com>
#
# Escapade Trip Planner is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
#
# Escapade Trip Planner is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with Escapade Trip
# Planner. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################################

import sys
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode

if __name__ == "__main__":
    sys.path.append('../..')

from escapade.core.map_item import LatLng, Bounds, MapItem

class MapItemBackend:
    def __init__(self):
        self._service_base_url = "http://nominatim.openstreetmap.org/search?"
        self._viewbox_france = "-4.87,51.14,8.32,42.30"
        self._viewbox_midi_pyrenees = "-0.30,45.06,3.45,42.55"
        self._viewbox_toulouse = "1.15,43.85,1.74,43.33"

    def search(self, query_string):
        l_request = Request(self._service_base_url + urlencode({'format': 'json',
                                                                'accept-language': 'fr_FR',
                                                                'email': 'pef.gomez@gmail.com',
                                                                'countrycodes': 'fr',
                                                                'addressdetails': 0,
                                                                'viewbox': self._viewbox_toulouse,
                                                                'bounded': 1,
                                                                'q': query_string}),
                            unverifiable=True)

        return json.loads(urlopen(l_request).read().decode('utf-8'),
                          object_hook=lambda r: MapItem(r['osm_id'],
                                                        r['osm_type'],
                                                        r['display_name'],
                                                        LatLng(r['lat'],
                                                               r['lon']),
                                                        Bounds(LatLng(r['boundingbox'][1],
                                                                      r['boundingbox'][2]),
                                                               LatLng(r['boundingbox'][0],
                                                                      r['boundingbox'][3]))))

if __name__ == "__main__":
    if len(sys.argv) == 2:
        l_store = MapItemStore()
        pprint.pprint([item.__dict__ for item in l_store.search(sys.argv[1])])
    else:
        raise SystemExit("Usage: " + sys.argv[0] + " <query_string>")
